package JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Users {
	
	public static Connection conn = SqlDB.getconn();
	//插入数据的方法
	public static int insert(UseInfo userinfo) {

		int i = 0;
		String sql = "insert into Users (LoginID,Name,Pwd,Role) values(?,?,?,?)";
		PreparedStatement pstmt;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			pstmt.setString(1, userinfo.getLoginID());
			pstmt.setString(2, userinfo.getName());
			pstmt.setString(3, userinfo.getPwd());
			pstmt.setInt(4, userinfo.getRole());
			i = pstmt.executeUpdate();
			pstmt.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
	//删除数据
	public static int delete(String LoginID) {

		int i = 0;
		String sql = "delete from Users where LoginID='" + LoginID + "'";
		PreparedStatement pstmt;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			i = pstmt.executeUpdate();
			System.out.println("resutl: " + i);
			pstmt.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
	//查询所有的表内容
	public static Integer getAll() {

		String sql = "select * from Users";
		PreparedStatement pstmt;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			int col = rs.getMetaData().getColumnCount();

			while (rs.next()) {
				for (int i = 1; i <= col; i++) {
					System.out.print(rs.getString(i) + "\t");
					if ((i == 2) && (rs.getString(i).length() < 8)) {
						System.out.print("\t");
					}
				}
				System.out.println("");
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	//修改单条语句密码
	public static int update(UseInfo userinfo) {

		int i = 0;
		String sql =  "update Users set pwd='" +userinfo.Pwd + "' where LoginID='" + userinfo.getLoginID() + "'";
		PreparedStatement pstmt;
		try {
			pstmt = (PreparedStatement) conn.prepareStatement(sql);
			i = pstmt.executeUpdate();
			System.out.println("resutl: " + i);
			pstmt.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
}
